<?php

class FacebookController extends Zend_Controller_Action
{
	function init() {}

	//we redirect the user to google for authentication
	function indexAction(){

		$facebook = new Myzen_Facebook();
		$user = $facebook->getUser();
		
		if ($user) {
  			try {
    			// Proceed knowing you have a logged in user who's authenticated.
    			$user_profile = $facebook->api('/me');
    			$this->_forward('completeauth');
    			return;
  			} catch (FacebookApiException $e) {
    			error_log($e);
    			$user = null;
  			}
		} //end user found

		// Login or logout url will be needed depending on current user state.

  		$loginUrl = $facebook->getLoginUrl(array('redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl().'/auth/facebook/completeauth/oauth_token/'.$this->_getParam('oauth_token').'/','req_perms' => 'email'));
		
		echo $loginUrl;
		exit;
		$this->_redirect($loginUrl);
		exit;
    
	} //end indexAction
	
	
	
	//when the provider returns the authenticated user, the rest is performed here
	function completeauthAction() {
		
		$facebook = new Myzen_Facebook();

		$user = $facebook->getUser();
		if ($user) {
  			try {
				$userProfile = $facebook->api('/me');
  			} catch (FacebookApiException $e) {
				$this->view->messageDisplay('You need to accept the request in order to login','error');
				$this->_redirect($this->view->baseUrl().'/auth/login/signup/');
				return;
  			}
  		} else {
 				$this->view->messageDisplay('You need to accept the request in order to login (no user)','error');
				$this->_redirect($this->view->baseUrl().'/auth/login/signup/');
				return; 			
  		}
		$details = Myzen_Facebook::getUserDetails($userProfile);
		$this->view->assign($details);
		$this->_forward('completeauthfromexternalprovider','index','auth');
		return;
	}//end completeauth
	
	
} //end class